package com.clothing.customization.service.impl;

import com.clothing.customization.repository.CustomOrderRepository;
import com.clothing.customization.service.OrderAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(readOnly = true)
public class OrderAnalysisServiceImpl implements OrderAnalysisService {

    @Autowired
    private CustomOrderRepository orderRepository;

    @Override
    public Map<String, Object> getOrderTrend(String type, Date startDate, Date endDate) {
        Map<String, Object> result = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        List<Double> amounts = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        SimpleDateFormat dateFormat;

        switch (type) {
            case "daily":
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                while (!calendar.getTime().after(endDate)) {
                    Date currentDate = calendar.getTime();
                    dates.add(dateFormat.format(currentDate));
                    
                    // 获取当天订单数据
                    Map<String, Object> dailyData = orderRepository.getDailyOrderStats(currentDate);
                    counts.add((Integer) dailyData.get("count"));
                    amounts.add((Double) dailyData.get("amount"));
                    
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                }
                break;

            case "weekly":
                dateFormat = new SimpleDateFormat("yyyy-ww");
                calendar.setFirstDayOfWeek(Calendar.MONDAY);
                while (!calendar.getTime().after(endDate)) {
                    Date weekStart = calendar.getTime();
                    dates.add(dateFormat.format(weekStart));
                    
                    // 获取本周订单数据
                    calendar.add(Calendar.DAY_OF_WEEK, 6);
                    Date weekEnd = calendar.getTime();
                    Map<String, Object> weeklyData = orderRepository.getOrderStatsBetween(weekStart, weekEnd);
                    counts.add((Integer) weeklyData.get("count"));
                    amounts.add((Double) weeklyData.get("amount"));
                    
                    calendar.add(Calendar.DAY_OF_WEEK, 1);
                }
                break;

            case "monthly":
                dateFormat = new SimpleDateFormat("yyyy-MM");
                while (!calendar.getTime().after(endDate)) {
                    Date monthStart = calendar.getTime();
                    dates.add(dateFormat.format(monthStart));
                    
                    // 获取本月订单数据
                    calendar.add(Calendar.MONTH, 1);
                    calendar.add(Calendar.DAY_OF_MONTH, -1);
                    Date monthEnd = calendar.getTime();
                    Map<String, Object> monthlyData = orderRepository.getOrderStatsBetween(monthStart, monthEnd);
                    counts.add((Integer) monthlyData.get("count"));
                    amounts.add((Double) monthlyData.get("amount"));
                    
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                }
                break;
        }

        result.put("dates", dates);
        result.put("counts", counts);
        result.put("amounts", amounts);
        return result;
    }

    @Override
    public Map<String, Object> getOrderDistribution(String type, Date startDate, Date endDate) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> data = new ArrayList<>();

        switch (type) {
            case "category":
                // 获取品类分布数据
                data = orderRepository.getCategoryDistribution(startDate, endDate);
                break;

            case "region":
                // 获取地区分布数据
                data = orderRepository.getRegionDistribution(startDate, endDate);
                break;

            case "channel":
                // 获取渠道分布数据
                data = orderRepository.getChannelDistribution(startDate, endDate);
                break;
        }

        // 计算占比
        double total = data.stream()
                .mapToDouble(item -> ((Number) item.get("value")).doubleValue())
                .sum();

        data.forEach(item -> {
            double value = ((Number) item.get("value")).doubleValue();
            item.put("percentage", String.format("%.2f", (value / total) * 100));
        });

        result.put("data", data);
        return result;
    }

    @Override
    public Map<String, Object> getOrderDetails(Date startDate, Date endDate, Integer page, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取分页数据
        List<Map<String, Object>> records = orderRepository.getOrderDetails(startDate, endDate, page, pageSize);
        
        // 获取总记录数
        long total = orderRepository.countOrdersBetween(startDate, endDate);
        
        // 处理数据，计算平均客单价和完成率
        records.forEach(record -> {
            double totalAmount = (Double) record.get("totalAmount");
            int orderCount = (Integer) record.get("orderCount");
            int completedCount = (Integer) record.get("completedCount");
            
            // 计算平均客单价
            record.put("avgAmount", orderCount > 0 ? totalAmount / orderCount : 0);
            
            // 计算完成率
            record.put("completionRate", orderCount > 0 ? (completedCount * 100.0 / orderCount) : 0);
        });
        
        result.put("records", records);
        result.put("total", total);
        return result;
    }
} 